<script setup lang="ts">
import { onMounted, ref, nextTick } from "vue";
import Food from "./food.vue";
import { useCartStore } from "@/store/cart";
import { useRouter } from "vue-router";
import Edit_button from "@/components/edit_button.vue";
import { apiDeviceGet, apiMenuGet, apirotatingGet } from "@/tool/request";
import { menu_fileType } from "@/tool/types";

const cartStore = useCartStore();
const router = useRouter();
const orderMenuRight = ref<HTMLElement>();
const foodPositions = ref<number[]>([]);

const goToCart = () => {
  router.push("/cart");
};

const updateFoodPositions = () => {
  nextTick(() => {
    const foods = orderMenuRight.value?.querySelectorAll(".food");
    foodPositions.value = Array.from(foods || []).map((food) => {
      return food.getBoundingClientRect().top;
    });
  });
};

const scrollToMenu = (index: number) => {
  menus_choose_index.value = index;
  if (orderMenuRight.value && foodPositions.value[index]) {
    orderMenuRight.value.scrollTo({
      top: foodPositions.value[index],
      behavior: "smooth",
    });
  }
};

const handleRightScroll = () => {
  if (!orderMenuRight.value) return;

  const scrollTop = orderMenuRight.value.scrollTop;
  const scrollPositions = foodPositions.value.map((pos) => pos - scrollTop);

  for (let i = 0; i < scrollPositions.length; i++) {
    if (
      scrollPositions[i] <= 100 &&
      (i === scrollPositions.length - 1 || scrollPositions[i + 1] > 100)
    ) {
      menus_choose_index.value = i;
      break;
    }
  }
};
const swipe_arr = ref<{ url: string }[]>([]);

const menus_choose_index = ref(0);

const menus = ref<menu_fileType[]>([]);

const foods = ref<any[]>([]);
const getMenu = () => {
  apiMenuGet().then((res) => {
    menus.value = res.data;
  });
};

const getFoods = ()=>{
  apiDeviceGet(0).then(res=>{
    foods.value = res.data
    menus.value.filter(item=>{
      foods.value.map(_food=>{
        if(item.id == _food.file_id){
          if(item.foods == undefined){
            item.foods = []
          }
          
          item.foods.push(_food)
        }
      })
      // if(item.id == )
    })
  })
}

onMounted(() => {
  // menus.value.map((item) => {
  //   foods.value.push(...(item.foods ?? []));
  // });
  updateFoodPositions();
  getMenu();
  apirotatingGet().then((res) => {
    swipe_arr.value = res.data;
    getFoods()
  });
  // headerAdd("无论我们能活多久，我们能够享受的只有无法分割的此刻，此外别无其他。");
});
</script>

<template>
  <div class="order">
    <van-swipe
      class="my-swipe"
      style="grid-area: a; position: relative; height: 200px"
      :autoplay="3000"
      lazy-render
    >
      <van-swipe-item v-for="item in swipe_arr">
        <img class="banner-img" :src="item.url" />
      </van-swipe-item>
    </van-swipe>
    <Edit_button style="position: absolute; right: 5px" @click="router.push('/upload')" />
    <!-- <div class="order-position" style="grid-area: b;" >
        <p><van-icon name="star-o" size="1.2rem" />{{ "德克士春熙路" }}</p>
        <p>成都市锦江区正科甲巷子1-67号二楼</p>
        <p>距离0.5km</p>
    </div> -->

    <div class="order-menu-left" style="grid-area: b; position: relative">
      <Edit_button
        style="position: absolute; top: -10px; left: 0px; z-index: 999"
        @click="router.push('/menu')"
      />
      <div class="menus-list">
        <div
          class="menu-item"
          v-for="(item, i) in menus"
          :class="[menus_choose_index == i ? 'choosed' : '']"
          :style="{}"
          @click="scrollToMenu(i)"
        >
          <van-image
            v-if="menus_choose_index == i && item.url.length > 0"
            width="60"
            height="40"
            :src="item.url"
          />
          <p style="color: #838383">{{ item.name }}</p>
        </div>
      </div>
    </div>
    <div
      class="order-menu-right"
      style="grid-area: c"
      ref="orderMenuRight"
      @scroll="handleRightScroll"
    >
      <Food v-for="item in foods" :food="item" />
    </div>
    <div class="cart-icon" style="grid-area: d">
      <van-badge :content="cartStore.totalItems" max="99">
        <van-icon name="shopping-cart-o" size="24" @click="goToCart" />
      </van-badge>
      <span style="color: red; margin-left: 15px"
        >¥{{ (cartStore.totalPrice || 0).toFixed(2) }}</span
      >

      <van-button
        round
        type="primary"
        size="small"
        @click="goToCart"
        style="margin-left: auto"
        v-if="(cartStore.totalPrice || 0) > 0"
      >
        去结算
      </van-button>
    </div>
  </div>
</template>

<style lang="scss" scope>
.order {
  &-menu {
    &-left {
      background-color: #fff;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

      .menus-list {
        .choosed {
          background: linear-gradient(90deg, #fef5e6, #fff) !important;
          position: relative;

          &::before {
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 4px;
            background-color: #ff9500;
          }
        }

        .menu-item {
          background: #fff;
          padding: 12px 15px;
          transition: all 0.3s ease;

          &:hover {
            background-color: #fef5e6;
          }

          p {
            font-size: 14px;
            margin-top: 5px;
          }
        }

        margin-top: 0;
      }

      min-height: calc(100vh - 350px);
      padding: 10px 0;
    }

    &-right {
      overflow-y: scroll;
      height: calc(100vh - 330px);
      background-color: #fff;
      border-radius: 8px;
    }
  }

  .banner-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 8px;
  }

  .cart-icon {
    width: 90%;
    background-color: #fff;
    padding: 12px 20px;
    display: flex;
    align-items: center;
    border-radius: 30px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    .van-badge {
      margin-right: 10px;
    }

    .price-display {
      font-size: 16px;
      font-weight: bold;
      color: #ff4444;
      margin-left: auto;
    }

    .van-button {
      margin-left: 15px;
      background: linear-gradient(90deg, #ff9500, #ff5000);
      border: none;
      box-shadow: 0 2px 6px rgba(255, 80, 0, 0.3);
    }
  }

  display: grid;
  gap: 10px;
  grid-template-areas: "a a" "b c" "d d";
  position: relative;
  grid-template-columns: auto 1fr;
  background-color: #f8f8f8;
}
</style>
